package com.itheima.sevice.impl;

import com.itheima.common.utils.POIUtils;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.OrderSettingDTO;
import com.itheima.pojo.OrderSettingVO;
import com.itheima.sevice.OrderSettingService;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

@Service
public class OrderSettingServiceImpl implements OrderSettingService {

    @Autowired
    private OrderSettingDao orderSettingDao;

    /**
     * 下载模板
     * @param response
     * @param filename
     */
    @Override
    public void download(HttpServletResponse response, String filename) {
        // 置流文件的编码格式（setHeader、setContentType）
        response.setHeader("content-Disposition", "attachment; filename=" + filename);
        response.setContentType("application/vnd.ms-excel;charset=gb2312");

        try (
                InputStream in = this.getClass().getClassLoader()
                        .getResourceAsStream("templates/" + filename);
                //通过输入流读取指定的Excel文件
                XSSFWorkbook excel = new XSSFWorkbook(in);
                // 通过输出流将Excel文件下载到客户端浏览器
                ServletOutputStream out = response.getOutputStream();
//                FileOutputStream out = new FileOutputStream(new File(filename));
        ){
            excel.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据日期修改可预约人数
     * @param orderSettingDTO
     * @return
     */
    @Override
    public Integer editNumberByOrderDate(OrderSettingDTO orderSettingDTO) {
        // 查询当前日期是否设置预约人数
        OrderSetting orderSetting = orderSettingDao.getByOrderDate(orderSettingDTO.getOrderDate());
        Integer recordCount = 0;
        if (orderSetting != null){
            // 之前设置过，则更新之前设置
            recordCount = orderSettingDao.editNumberByOrderDate(orderSettingDTO);
        }else {
            // 未设置过，则插入该设置数据
            recordCount = orderSettingDao.insert(orderSettingDTO);
        }
        return recordCount;
    }

    /**
     * 根据年月查询预约设置
     * @param month
     * @return
     */
    @Override
    public List<OrderSettingVO> getOrderSettingByMonth(String month) {
        String[] date = month.split("-");
        LocalDate begin = LocalDate.of(Integer.valueOf(date[0]), Integer.valueOf(date[1]), LocalDate.MIN.getDayOfMonth());
        LocalDate end = begin.plusDays(begin.lengthOfMonth()-1);
        List<OrderSetting> orderSettingList = orderSettingDao.getOrderSettingByMonth(begin, end);
        List<OrderSettingVO> orderSettingVOList = new ArrayList<>();

        for (OrderSetting orderSetting : orderSettingList) {
            OrderSettingVO orderSettingVO = new OrderSettingVO();
            orderSettingVO.setNumber(orderSetting.getNumber());
            orderSettingVO.setReservations(orderSetting.getReservations());
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(orderSetting.getOrderDate());
            orderSettingVO.setDate(calendar.get(Calendar.DAY_OF_MONTH));

            orderSettingVOList.add(orderSettingVO);
        }

        return orderSettingVOList;
    }

    /**
     * 上传excel文件
     * @param excelFile
     * @return
     */
    @Override
    public Integer upload(MultipartFile excelFile) throws Exception {
        // 校验文件是否合法
        POIUtils.checkFile(excelFile);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");

        List<String[]> excelData = POIUtils.readExcel(excelFile);
        Integer recordCount = 0;

        for (String[] row : excelData) {
            OrderSettingDTO orderSettingDTO = new OrderSettingDTO();
            orderSettingDTO.setOrderDate(LocalDate.parse(row[0], formatter));
            orderSettingDTO.setNumber(Integer.valueOf(row[1]));
            // 将数据插入到数据库中
            recordCount += editNumberByOrderDate(orderSettingDTO);
        }
        return recordCount;
    }
}
